package worldModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import battleFieldModel.Point;

public class SaveGameHelper {

    public static Navigator openGame() {

	Navigator nav = null;

	ObjectInputStream ois = null;
	try {
	    ois = new ObjectInputStream(new FileInputStream(new File(
		    "navigator.dat")));
	    try {
		nav = (Navigator) ois.readObject();
	    } catch (ClassNotFoundException e) {
		System.out.println("Aww Snap!");
		// Retry with new navigator
		saveNewNavigator();
		openGame();
	    }
	} catch (FileNotFoundException e) {
	    // Retry with new navigator
	    saveNewNavigator();
	    openGame();
	} catch (IOException e) {
	    e.printStackTrace();
	}

	return nav;
    }

    /**
     * Create a new navigator.dat file with 1 of each objects.
     */

    public static void saveNewNavigator() {

	File f = new File("navigator.dat");
	Navigator newNav = new Navigator();
	newNav.setLocation(new Point(10, 10));
	ObjectOutputStream outputStream = null;
	try {
	    outputStream = new ObjectOutputStream(new FileOutputStream(f));

	    newNav.addItem(new SmallHeal());
	    newNav.addItem(new MediumHeal());
	    newNav.addItem(new LargeHeal());

	    outputStream.writeObject(newNav);

	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}

    }

    /**
     * Save the passed navigator as navigator.dat in the disk.
     * 
     * @param n
     */

    public static void saveGame(Navigator n) {

	File f = new File("navigator.dat");

	ObjectOutputStream outputStream = null;
	try {
	    outputStream = new ObjectOutputStream(new FileOutputStream(f));
	    outputStream.writeObject(n);
	} catch (FileNotFoundException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}

    }
}
